package lv.solcraft.replication.server.rest.restlets;

import java.io.IOException;

import lv.solcraft.replication.server.bdb.Database;
import lv.solcraft.replication.server.bdb.TxTemplateNoResult;
import lv.solcraft.replication.server.model.Field;
import lv.solcraft.replication.server.model.Oper;
import lv.solcraft.replication.server.model.OperId;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Resource;
import org.restlet.resource.Variant;
import org.springframework.util.Assert;

import com.noelios.restlet.application.DecodeRepresentation;
import com.sleepycat.je.Transaction;

public class OperFieldsResource extends Resource {

    private Database database;
    private OperId operId;

    public void setDatabase(Database database) {
        this.database = database;
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        long originSiteId = Long.parseLong(request.getAttributes().get("originSiteId").toString());
        long originOperId = Long.parseLong(request.getAttributes().get("originOperId").toString());
        operId = new OperId(originSiteId, originOperId);
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public boolean allowPut() {
        return true;
    }

    @Override
    public void handlePut() {
        JSONArray fieldsJson = null;
        try {
            fieldsJson = JSONArray.fromObject(new DecodeRepresentation(getRequest().getEntity()).getText());
        } catch (IOException e) {
            throw new IllegalArgumentException("Could not read fields JSON array from request", e);
        }
        final JSONArray finalFieldsJson = fieldsJson;
        new TxTemplateNoResult(database) {
            @Override
            protected void executeInTxNoResult(Transaction tx) throws Exception {
                Oper oper = database.getOperDataAccess().find(operId);
                Assert.notNull(oper, "Oper not found, id " + operId);
                oper.removeAllFields();
                for (int i = 0; i < finalFieldsJson.size(); i++) {
                    JSONObject fieldJson = finalFieldsJson.getJSONObject(i);
                    Field field = Field.create(fieldJson);
                    oper.addField(field);
                }
                oper.persist();
            }
        }.execute();
    }
}
